class StudentOperations:
    def __init__(self, students, grades):
        self.students = students['students']
        self.grades = grades['grades_per_course']
    
    
    def get_all_students(self):
        return [student['username'] for student in self.students]
    
    def get_student_information(self, username):
        student = next((s for s in self.students if s['username'] == username), None)
        if not student:
            return None

        info_lines = [
            "═" * 40,
            f"students' information - {student['username']}",
            "═" * 40,
            f"name: {student.get('fullName', 'N/A')}",
            f"age: {student.get('age', 'N/A')}",
            f"school: {student.get('school', 'N/A')}"
        ]

        if 'interests' in student and student['interests']:
            info_lines.append(f"\n🎯 interests : {', '.join(student['interests'])}")

        if 'followed_courses' in student and student['followed_courses']:
            info_lines.append("\n📖 Selected courses:")
            for course_id in student['followed_courses']:
                info_lines.append(f"  - {course_id}")

        if 'relations' in student and student['relations']:
            info_lines.append(f"\n👥 Social connections: {', '.join(student['relations'])}")

        info_lines.append("═" * 40)
        return "\n".join(info_lines)
    
    def get_student_grades(self, username):
        grades = {}
        for course_id, course_grades in self.grades.items():
            if username in course_grades:
                grades[course_id] = course_grades[username]
        return grades
    
    def get_student_courses(self, username):
        student = self.get_student_information(username)
        return student['followed_courses'] if student else []
            

    def _get_raw_student(self, username):
        return next((s for s in self.students if s['username'] == username), None)

    def get_course_ranking(self, course_id):
        if course_id not in self.grades:  
            return None
    
        student_scores = []
        for username, scores in self.grades[course_id].items():
            student = self._get_raw_student(username)  
            avg_score = sum(scores) / len(scores)
            student_scores.append({
                'username': username,
                'fullName': student['fullName'] if student else 'Unknown',
                'average': avg_score,
                'scores': scores
            })

        return sorted(student_scores, key=lambda x: x['average'], reverse=True)
    
    def sort_students_name(self,by='name'):
        if by == 'name':
            the_key = lambda x : x['fullName']
        else:
            the_key = lambda x : x['username']
            
        return sorted(self.students,key = the_key)